package com.ruoyi.bus.domain.map;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * session缓存
 */
public class MapSessionCache {
    
    private static RedisCache redisCache;
    
    private static RedisCache getRedisCache(){
        if(redisCache == null){
            redisCache = SpringUtils.getBean(RedisCache.class);
        }
        return redisCache;
    }
    
    private static Map<String, MapSocketSession> sessionMap = new ConcurrentHashMap<String, MapSocketSession>();

    public static MapSocketSession getSession(String key) {
        String result = getRedisCache().getCacheObject("socket_token:" + key);
        if(StringUtils.isBlank(result)){//说明过期
            sessionMap.remove(key);
            return null;
        }
        return sessionMap.get(key);
    }

    public static void setSession(String key, MapSocketSession webSocketSession){
        getRedisCache().setCacheObject("socket_token:" + key, "ok",3, TimeUnit.MINUTES);
        sessionMap.put(key, webSocketSession);
    }

    public static Collection getAllSession(){
        return getRedisCache().keys("socket_token:*");
    }

    public static void removeSession(String key){
        getRedisCache().deleteObject("socket_token:" + key);
    }

}
